package com.keio.handler;

import com.keio.common.protocol.ProxyMessage;
import com.mysql.cj.xdevapi.Client;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;

/**
 * @Description 将内网channel的数据 转发到  服务端上的处理器
 * @author KEIO  on 2022/1/14.
 * @version 1.0
 */
@Slf4j
public class LocalHandler extends ChannelInboundHandlerAdapter {

    private ClientHandler clientHandler;

    private ChannelHandlerContext localCtx;

    private String localChannelId;

    public LocalHandler (ClientHandler clientHandler, String channelId) {
        this.clientHandler = clientHandler;
        this.localChannelId = channelId;
    }

    public ChannelHandlerContext getLocalCtx () {
        return localCtx;
    }



    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.localCtx = ctx;
        log.info("与本地端口建立连接  端口地址为{}" , localCtx.channel().remoteAddress());

    }

    /**
     * 连接关闭 回传disconnected 信息
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ProxyMessage proxyMessage = new ProxyMessage();
        proxyMessage.setType(ProxyMessage.TYPE_DISCONNECTED);
        HashMap<String, Object> metaData = new HashMap<String, Object>();
        metaData.put("channelId" , localChannelId);
        ctx.writeAndFlush(proxyMessage);

        log.info("本地连接断开 , 端口为{}" , ctx.channel().remoteAddress());

    }

    /**
     * @Description 执行数据转发到 服务器
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        byte[] data = (byte[]) msg;
        ProxyMessage proxyMessage = new ProxyMessage();
        HashMap<String ,Object>  metaData = new HashMap<String, Object>();
        metaData.put("channelId",  localChannelId);

        proxyMessage.setType(ProxyMessage.TYPE_DATA);
        proxyMessage.setMetaData(metaData);
        proxyMessage.setData(data);

        ctx.writeAndFlush(proxyMessage);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.channel().close();
        cause.printStackTrace();
        log.info("连接中断");
    }
}
